package com.zjh.service.impl;

import com.zjh.dao.sysUserDao;
import com.zjh.feign.FeignUser;
import com.zjh.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private FeignUser feignUser;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Response<sysUserDao> user = feignUser.queryUsrByUsrname(username);

        if (user.getObj() == null) {
            throw new UsernameNotFoundException("User not found");
        }

        Collection<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));

        return User.builder()
                .username(user.getObj().getUsername())
                .password(user.getObj().getPasswordHash())
                .authorities(authorities)
                .build();
    }
}
